package itsm.isperp.module.service.project;

import itsm.isperp.control.form.table.TreeTable;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataRequest;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.utils.TreeNodeUtils;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.project.ProjectMonitorDTO;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.repository.project.ProjProjectMapper;
import itsm.isperp.module.repository.project.ProjProjectMemberMapper;
import itsm.isperp.module.repository.project.ProjProjectServiceMapper;
import itsm.isperp.module.service.slm.SlmServiceAgreementService;
import itsm.isperp.module.service.task.TskPlanTaskService;
import itsm.isperp.workflow.utils.BpmConst;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * 项目管理服务类
 * 
 * @author lizx
 * @date 2013-3-2
 * @version V1.0
 * 
 */
@Service
public class ProjProjectService extends BaseService<ProjProject> {

	/**
	 * 未发布
	 */
	public static final String STAGE_UNPUBLICED = "未发布";
	/**
	 * 已发布
	 */
	public static final String STAGE_PUBLICED = "已发布";
	/**
	 * 已归档
	 */
	public static final String STAGE_FINISHED = "已归档";

	@Autowired
	protected ProjProjectMapper projProjectMapper;

	@Autowired
	protected ProjProjectServiceMapper projProjectServiceMapper;

	@Autowired
	protected ProjProjectMemberMapper projProjectMemberMapper;

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Override
	public ProjProjectMapper getRepository() {
		return this.projProjectMapper;
	}

	//
	// @Override
	// public int saveOrUpdate(ProjProject entity) {
	// Assert.notNull(entity, "对象不能为空");
	//
	// if (StringUtils.isEmpty(entity.getId())) {
	// entity.setId(HibernateUUIDGenerator.generate());
	// return this.getRepository().save(entity);
	// } else {
	//
	// if (this.getRepository().existsByClass(entity.getId(),
	// entity.getClass()) == null)
	//
	// return this.getRepository().save(entity);
	// else
	// this.dynamicUpdateEntity(entity);
	// return 1;
	// }
	// }

	@Override
	public ResultMessage delete(String id) {
		Assert.notNull(id, "id不能为空");
		// 利用泛型获取class

		// 服务范围
		this.projProjectServiceMapper.deleteByProjectId(id);
		// 人员
		// this.projProjectMemberMapper.
		// 预算
		ProjCostItemService projCostItemService = ContextHolder
				.getSpringBean("projCostItemService");

		projCostItemService.deleteByProjectId(id);

		// 计划
		TskPlanTaskService tskPlanTaskService = ContextHolder
				.getSpringBean("tskPlanTaskService");
		tskPlanTaskService.deleteByProjectId(id);

		// 服务目录
		SlmServiceAgreementService slmServiceAgreementService = ContextHolder
				.getSpringBean("slmServiceAgreementService");
		slmServiceAgreementService.deleteByProjectId(id);

		this.getRepository().deleteByClass(id, ProjProject.class);
		return ResultMessage.success();
	}

	/**
	 * 查询已发布的项目
	 * 
	 * @param fields
	 *            列数组
	 * 
	 * @return 项目列表
	 */
	public Map<String, Object> getProjectStageAndStatus(String id) {

		return this.findOneToMap(id, "stage", "status", "process_id");

	}

	/**
	 * 查询已发布的项目
	 * 
	 * @param fields
	 *            列数组
	 * 
	 * @return 项目列表
	 */
	public List<ProjProject> findAllPublished(String... fields) {

		JqGridRequest req = new JqGridRequest();
		req.addFilterRule("stage", JqGridFilterRuleOp.eq, STAGE_PUBLICED);

		req.isPageable(false);
		req.setSelectColumns(fields);

		return this.projProjectMapper.findAllByRequest(req);
	}
	
	public List<Map<String,Object>> findAllDetailPublished(String... fields) {
		JqGridRequest req = new JqGridRequest();
		req.addFilterRule("stage", JqGridFilterRuleOp.eq, STAGE_PUBLICED);
		req.isPageable(false);
		req.setSelectColumns(fields);
		return this.projProjectMapper.findAllDetailByRequest(req);
	}

	/**
	 * 更新项目资产配置项描述
	 * 
	 * @param projectId
	 *            项目Id
	 * @param confDescription
	 *            资产配置项描述
	 */
	public void updateConfDescription(String projectId, String confDescription) {
		Assert.hasText(projectId);

		ProjProject proj = new ProjProject();
		proj.setId(projectId);
		proj.setConfDescription(confDescription);
		Set<String> includeColumns = new HashSet<>();
		includeColumns.add("confDescription");

		this.getRepository().dynamicSpecificUpdate(proj, includeColumns);

	}

	/**
	 * 获取项目预算
	 * 
	 * @param projectId
	 * @param projCostTemplateId
	 */
	public List<Map<String, Object>> getCost(String projectId,
			String projCostTemplateId) {
		List<Map<String, Object>> list = this.getRepository().getCost(
				projectId, "/" + projCostTemplateId + "/%");

		// 重新排序
		list = TreeNodeUtils.sortTree(list);

		return list;
	}

	/**
	 * 获取项目预算
	 * 
	 * @param projectId
	 * @param projCostTemplateId
	 */
	public List<Map<String, Object>> getCostAccountingEntryAmount(
			String projectId) {
		return this.getRepository().getCostAccountingEntryAmount(projectId);

	}

	public TreeTable getCostTreeTable(String projectId,
			String projCostTemplateId) {

		return getCostTreeTable(getCost(projectId, projCostTemplateId));

	}

	private TreeTable getCostTreeTable(List<Map<String, Object>> costs) {
		TreeTable tt = new TreeTable();
		for (Map<String, Object> m : costs) {
			long count_id = Long.valueOf(m.get("count_id").toString());
			if (count_id == 1) {
				String id = (String) m.get("id");
				String treenodeName = (String) m.get("treenode_name_path");
				String code = (String) m.get("code");
				String cal = (String) m.get("calculate_formula");
				Object objValue = m.get("amount");
				String value = "";
				if (objValue != null) {
					value = objValue.toString();
				}

				tt.addRow(id, treenodeName, code, cal, value);
			}
		}

		return tt;
	}

	/**
	 * 更新 项目的预算模板id
	 * 
	 * @param projectId
	 *            项目id
	 * @param projCostTemplateId
	 *            项目预算模板id
	 */
	public void updateCostTemplateId(String projectId, String projCostTemplateId) {
		Assert.hasText(projectId);

		ProjProject proj = new ProjProject();
		proj.setId(projectId);
		proj.setProjCostTemplateId(projCostTemplateId);
		Set<String> includeColumns = new HashSet<>();
		includeColumns.add("projCostTemplateId");

		this.getRepository().dynamicSpecificUpdate(proj, includeColumns);
	}

	/**
	 * 更新项目分类
	 * 
	 * @param projectId
	 *            项目id
	 * @param projCategoryId
	 *            分类id
	 */
	public void updateProjectCategory(String projectId, String projCategoryId) {
		Assert.hasText(projectId);

		ProjProject proj = new ProjProject();
		proj.setId(projectId);
		proj.setProjCategoryId(projCategoryId);
		Set<String> includeColumns = new HashSet<>();
		includeColumns.add("projCategoryId");

		this.getRepository().dynamicSpecificUpdate(proj, includeColumns);
	}

	/**
	 * 根据项目id获取到项目金额
	 * 
	 * @param projectId
	 *            项目id
	 * @return 项目金额
	 */
	public int getProjectAccount(String projectId) {

		String sql = "SELECT account FROM proj_project WHERE id='" + projectId
				+ "'";
		Map<String, Object> result = jdbcTemplate.queryForMap(sql);
		if (MapUtils.isNotEmpty(result)) {
			return Integer.parseInt(result.get("account").toString());
		}

		return 0;
	}

	/**
	 * 项目归档 重要逻辑：1、将项目状态置为“关闭” 2、建立项目与客户资产之间的关联关系
	 * 
	 * @param projectId
	 */
	public void finishProject(String projectId) {
		// 更新项目状态
		projProjectMapper.updateProjectStage(projectId, STAGE_FINISHED);
		// 建立项目与资产的关联关系
		projProjectMapper.createRelationFromProjectToCI(projectId);
	}

	/**
	 * 获取项目配置项的分类列表及统计数据
	 * 
	 * @param projectId
	 * @return
	 */
	public List<Map<String, Object>> getLibraryProjectCiCategory(
			String projectId) {

		return this.jdbcTemplate
				.queryForList(
						"SELECT c.id, c.name,COUNT(c.id) count_id "
								+ "FROM proj_relation_ci a LEFT JOIN "
								+ "conf_ci b ON a.ciid=b.id AND a.project_id=? "
								+ "LEFT JOIN conf_category c  ON b.conf_category_id = c.id    WHERE c.id IS NOT NULL GROUP BY c.id ",
						projectId);
	}

	/**
	 * 获取项目监控列表（根据用户帐号获取其关联的项目）
	 * 
	 * @param 用户帐号
	 */
	public DataResponse<ProjectMonitorDTO> getProjectMonitorLists(
			JqGridRequest request) {
		// 更新项目状态
		return projProjectMapper.getProjectMonitorLists(request);

	}

	/**
	 * 获取已归档项目的配置项
	 * 
	 * @param req
	 *            数据请求
	 * @return 相应结果
	 */
	public DataResponse<ConfCi> findProjectCiByRequest(DataRequest req) {
		return this.getRepository().findProjectCiByRequest(req);
	}

	/**
	 * 获取项目的所有成员
	 * 
	 * @param projectId
	 * @return
	 */
	public List<Map<String, Object>> findAllMemberByProjectId(String projectId) {

		String sql = " LEFT JOIN (SELECT COUNT(task_executer) AS process_count,task_executer FROM ( "
				+ BpmConst.getQueryTaskSql("incidentProcess")
				+ ")t GROUP BY task_executer)t ON t.task_executer=b.name ";

		return this.projProjectMemberMapper.findAllMemberByProjectId(projectId,
				sql);

	}
	// public DataResponse<ProjProject> findAll(DataRequest request) {
	//
	// return this.getRepository().findAllByRequest(request);
	// }
	//
	// public DataResponse<Map<String, Object>> findAllDetailByRequest(
	// DataRequest request) {
	//
	// return this.getRepository().findAllDetailByRequest(request);
	// }
	//
	// public DataResponse<Map<String, Object>> findAllDetailByRequest2(
	// DataRequest request) {
	//
	// return this.getRepository().findAllDetailByRequest(request);
	// }
}
